#include "mysqlManager.h"

SqlManager::SqlManager(/* args */)
{
     this->con =mysql_init(NULL);//初始化数据库句柄
    //连接数据库
    auto ret = mysql_real_connect(con,"127.0.0.1","root","zxy123456"
    ,"tallyBook",0,NULL,CLIENT_MULTI_STATEMENTS);
    if(ret==nullptr){
        cout<<"connect datdabasa fail ! "<<endl;
        return -1;
    }

}

SqlManager::~SqlManager()
{
    //需要释放数据库句柄吗？

}

class SqlManager::Imple
{
private:
    /* data */
public:
    Imple(/* args */);
    ~Imple();
};

SqlManager::Imple::Imple(/* args */)
{
}

SqlManager::Imple::~Imple()
{
}

bool passwd_cmp (LoginInfo info_tocmp){
//查询数据库
auto search_res = mysql_query(this->con,"select * from user;");
//获取查询结果
auto result =mysql_store_result(this->con);
int col = mysql_num_fields(result);
int row=mysql_num_rows(result);
//对比部分
if(search_res==0&&row!=0){
    for(int i=0;i<result->row_count;i++){
        auto info=mysql_fetch_row(result);
        if((strcmp(info[0],info_tocmp.name)==0)&&strcmp(info[1],info_tocmp.passwd)==0)
        { 
            return true;
        }
    return false;
    }
}
}



bool SqlManager::SqlQueryUser(char name [64]){
    //查询数据库
    auto search_res = mysql_query(this->con,"select * from user;");
    //获取查询结果
    auto result =mysql_store_result(this->con);
    int col = mysql_num_fields(result);
    int row=mysql_num_rows(result);
    //user表结构
                                                    /*    struct ReginstInfo
                                                    {
                                                        char            name[64];
                                                        char            passwd[32];
                                                        char            phone[11];
                                                        char            email[64];
                                                    };*/

    //对比部分
     if(search_res==0&&row!=0){
        for(int i=0;i<result->row_count;i++){
            auto info=mysql_fetch_row(result);
            if(strcmp(info[0],name)==0){return true;}//用户已存在
        }
        return false;//用户不存在
    }
}

bool SqlManager::SqlUserRegist(ReginstInfo info){
    char insert[200];
    string str ="INSERT INTO user (name,passwd,phone,email) 
    VALUE (""'" +info.name +"'"+"'"+info.passwd+"'"+"'"+info.phone+"'"+"'"+info.email+"'"")";
    strcpy(insert,str.c_str());
    if(mysql_query(this->con,insert)){
        return false;
    }
    return true;
}
bool SqlTallyRecord(TallyInfo info){
    char insert[200];
    string str ="INSERT INTO tallyRecord (name,passwd,phone,email) 
                VALUE (""'" +info.type +"'"+"'"+info.money+"'"+
                        "'"+info.account+"'"+"'"+info.useage+"'"
                        +"'"+info.time+"'"")";
    strcpy(insert,str.c_str());
    if(mysql_query(this->con,insert)){
        return false;//记录失败
    }
    return true;}//记录成功